package com.example.vaultmysql.controller;

import com.example.vaultmysql.dto.VaultConnectionTestResult;
import com.example.vaultmysql.dto.DatabaseCredentials;
import com.example.vaultmysql.service.VaultService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * Vault控制器
 * 提供Vault相关的API接口
 * 
 * @author System
 * @version 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/api/vault")
@CrossOrigin(origins = "*")
public class VaultController {

    @Autowired
    private VaultService vaultService;

    /**
     * 测试Vault连接
     */
    @GetMapping("/test-connection")
    public ResponseEntity<VaultConnectionTestResult> testConnection() {
        try {
            VaultConnectionTestResult result = vaultService.testConnection();
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("Vault连接测试失败", e);
            VaultConnectionTestResult result = VaultConnectionTestResult.failure(
                "连接测试失败: " + e.getMessage(), 
                0
            );
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 获取Vault健康状态
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> getHealth() {
        try {
            Map<String, Object> health = vaultService.getVaultHealth();
            return ResponseEntity.ok(health);
        } catch (Exception e) {
            log.error("获取Vault健康状态失败", e);
            return ResponseEntity.ok(Map.of(
                "status", "error",
                "message", e.getMessage(),
                "timestamp", System.currentTimeMillis()
            ));
        }
    }

    /**
     * 获取数据库凭证
     */
    @GetMapping("/credentials/{path}")
    public ResponseEntity<DatabaseCredentials> getCredentials(@PathVariable String path) {
        try {
            // 确保路径以/开头
            if (!path.startsWith("/")) {
                path = "/" + path;
            }
            
            DatabaseCredentials credentials = vaultService.getDatabaseCredentials(path);
            return ResponseEntity.ok(credentials);
        } catch (Exception e) {
            log.error("获取数据库凭证失败: path={}", path, e);
            return ResponseEntity.badRequest().body(
                DatabaseCredentials.invalid("获取凭证失败: " + e.getMessage())
            );
        }
    }

    /**
     * 存储数据库凭证
     */
    @PostMapping("/credentials/{path}")
    public ResponseEntity<Map<String, Object>> storeCredentials(
            @PathVariable String path,
            @RequestBody Map<String, String> credentials) {
        try {
            // 确保路径以/开头
            if (!path.startsWith("/")) {
                path = "/" + path;
            }
            
            // 验证必要字段
            if (!credentials.containsKey("username") || !credentials.containsKey("password")) {
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "缺少必要字段: username 和 password"
                ));
            }
            
            vaultService.storeDatabaseCredentials(path, credentials);
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "凭证存储成功",
                "path", path
            ));
        } catch (Exception e) {
            log.error("存储数据库凭证失败: path={}", path, e);
            return ResponseEntity.badRequest().body(Map.of(
                "success", false,
                "message", "存储凭证失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 删除数据库凭证
     */
    @DeleteMapping("/credentials/{path}")
    public ResponseEntity<Map<String, Object>> deleteCredentials(@PathVariable String path) {
        try {
            // 确保路径以/开头
            if (!path.startsWith("/")) {
                path = "/" + path;
            }
            
            vaultService.deleteDatabaseCredentials(path);
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "凭证删除成功",
                "path", path
            ));
        } catch (Exception e) {
            log.error("删除数据库凭证失败: path={}", path, e);
            return ResponseEntity.badRequest().body(Map.of(
                "success", false,
                "message", "删除凭证失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 检查Vault路径是否存在
     */
    @GetMapping("/path-exists/{path}")
    public ResponseEntity<Map<String, Object>> checkPathExists(@PathVariable String path) {
        try {
            // 确保路径以/开头
            if (!path.startsWith("/")) {
                path = "/" + path;
            }
            
            boolean exists = vaultService.pathExists(path);
            
            return ResponseEntity.ok(Map.of(
                "exists", exists,
                "path", path,
                "timestamp", System.currentTimeMillis()
            ));
        } catch (Exception e) {
            log.error("检查Vault路径失败: path={}", path, e);
            return ResponseEntity.badRequest().body(Map.of(
                "exists", false,
                "path", path,
                "error", e.getMessage()
            ));
        }
    }

    /**
     * 获取Vault配置信息（不包含敏感信息）
     */
    @GetMapping("/config")
    public ResponseEntity<Map<String, Object>> getVaultConfig() {
        try {
            // 这里应该从配置中获取Vault信息，但不包含敏感数据
            return ResponseEntity.ok(Map.of(
                "vaultUrl", "http://localhost:8200",
                "authMethod", "AppRole",
                "namespace", "default",
                "status", "configured",
                "timestamp", System.currentTimeMillis()
            ));
        } catch (Exception e) {
            log.error("获取Vault配置失败", e);
            return ResponseEntity.badRequest().body(Map.of(
                "status", "error",
                "message", e.getMessage()
            ));
        }
    }

    /**
     * 批量测试多个路径的凭证
     */
    @PostMapping("/test-credentials")
    public ResponseEntity<Map<String, Object>> testCredentials(@RequestBody Map<String, String> paths) {
        try {
            Map<String, Object> results = Map.of();
            
            for (Map.Entry<String, String> entry : paths.entrySet()) {
                String name = entry.getKey();
                String path = entry.getValue();
                
                try {
                    DatabaseCredentials credentials = vaultService.getDatabaseCredentials(path);
                    results.put(name, Map.of(
                        "success", credentials.isValid(),
                        "path", path,
                        "hasUsername", credentials.getUsername() != null,
                        "hasPassword", credentials.getPassword() != null
                    ));
                } catch (Exception e) {
                    results.put(name, Map.of(
                        "success", false,
                        "path", path,
                        "error", e.getMessage()
                    ));
                }
            }
            
            return ResponseEntity.ok(Map.of(
                "results", results,
                "timestamp", System.currentTimeMillis()
            ));
        } catch (Exception e) {
            log.error("批量测试凭证失败", e);
            return ResponseEntity.badRequest().body(Map.of(
                "success", false,
                "message", e.getMessage()
            ));
        }
    }
}